import java.io.BufferedWriter;
import java.io.IOException;
import java.io.PrintStream;
import java.net.Socket;
import java.util.Scanner;

/**
 * Created by PZhang on 2015/8/27.
 */
public class OutThread implements Runnable {
    Socket socket;
    BufferedWriter bufferedWriter = null;
    boolean flag = true;
    Scanner scanner = new Scanner(System.in);
    String userinput;
    PrintStream printStream = null;

    public OutThread(Socket socket) {
        this.socket = socket;
    }

    /**
     * When an object implementing interface <code>Runnable</code> is used
     * to create a thread, starting the thread causes the object's
     * <code>run</code> method to be called in that separately executing
     * thread.
     * <p>
     * The general contract of the method <code>run</code> is that it may
     * take any action whatsoever.
     *
     * @see Thread#run()
     */
    @Override
    public void run() {
        while (flag) {
            try {
                if (!socket.isClosed()) {

                    printStream = new PrintStream(socket.getOutputStream(),true);
                    userinput = scanner.next();
                    if (userinput.equals("quit")){
                        flag=false;
                    }else{
                        printStream.println(userinput);
                    }
                } else {
                    flag = false;

                }
            } catch (IOException e) {

                e.printStackTrace();
            }

        }
        try {
            bufferedWriter.close();
            socket.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
